package com.gutsyzhan.bilibili.service.impl;

import com.gutsyzhan.bilibili.constant.UserConstant;
import com.gutsyzhan.bilibili.dao.UserFollowingDao;
import com.gutsyzhan.bilibili.domain.FollowingGroup;
import com.gutsyzhan.bilibili.domain.User;
import com.gutsyzhan.bilibili.domain.UserFollowing;
import com.gutsyzhan.bilibili.domain.UserInfo;
import com.gutsyzhan.bilibili.exception.ConditionException;
import com.gutsyzhan.bilibili.service.FollowingGroupService;
import com.gutsyzhan.bilibili.service.UserFollowingService;
import com.gutsyzhan.bilibili.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserFollowingServiceImpl implements UserFollowingService {
    @Resource
    private UserFollowingDao userFollowingDao;

    @Resource
    private FollowingGroupService followingGroupService;

    @Resource
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserFollowings(UserFollowing userFollowing){
        Long followingId = userFollowing.getFollowingId();
        Long userId = userFollowing.getUserId();
        if(userId.equals(followingId)){
            throw new ConditionException("不能关注自己!");
        }
        Long groupId = userFollowing.getGroupId();
        //如果用户没传groupId，那么使用默认分组
        FollowingGroup followingGroup;
        if(groupId == null){
            followingGroup = followingGroupService.getByType(UserConstant.USER_FOLLOWING_GROUP_TYPE_DEFAULT);
            userFollowing.setGroupId(followingGroup.getId());
        }else{
            //传了分组id则判断分组是否存在
            followingGroup = followingGroupService.getById(groupId);
            if(followingGroup == null){
                throw new ConditionException("关注的分组不存在!");
            }
        }
        //判断关注的人是否存在
        User user = userService.getUserById(followingId);
        if(user == null){
            throw new ConditionException("关注的用户不存在!");
        }
        //添加关注信息，
        // 一种方式：先查询是否存在，存在则删除，后插入；否则直接插入（没有删除标识）
        // 另一种一种方式：先查询是否存在已逻辑删除的记录，存在则修改记录，否则直接插入（有删除标识）
        Integer count = userFollowingDao.getNormalOrDeleteUserFollowing(userId, followingId, UserConstant.DELETE_FLAG);
        if(count > 0){
            userFollowingDao.updateNormalOrDeleteUserFollowing(userId, followingId, UserConstant.NORMAL_FLAG);
        }else{
            Date now = new Date();
            userFollowing.setCreateTime(now);
            userFollowing.setUpdateTime(now);
            userFollowingDao.addUserFollowings(userFollowing);
        }
    }

    @Override
    public List<FollowingGroup> getUserFollowings(Long userId){
        //1、获取用户关注列表
        List<UserFollowing> userFollowingList = userFollowingDao.getUserFollowings(userId);
        Set<Long> followingIds = userFollowingList.stream().map(UserFollowing::getFollowingId).collect(Collectors.toSet());
        List<UserInfo> userInfoList = new ArrayList<>();
        //2、根据关注用户的id查询所关注用户的基本信息
        if(!CollectionUtils.isEmpty(followingIds)){
            userInfoList = userService.getUserInfoByUserIds(followingIds);
        }
        for (UserFollowing userFollowing : userFollowingList) {
            for (UserInfo userInfo : userInfoList) {
                if(userFollowing.getFollowingId().equals(userInfo.getUserId())){
                    userFollowing.setUserInfo(userInfo);
                }
            }
        }
        //3、将关注的用户按照关注分组进行分类
        List<FollowingGroup> groupList = followingGroupService.getByUserId(userId);
        //全部关注
        FollowingGroup allGroup = new FollowingGroup();
        allGroup.setName(UserConstant.USER_FOLLOWING_GROUP_ALL_NAME);
        allGroup.setUserId(userId);
        Date now = new Date();
        allGroup.setCreateTime(now);
        allGroup.setUpdateTime(now);
        allGroup.setIsDelete(0);
        allGroup.setFollowingUserInfoLists(userInfoList);
        List<FollowingGroup> result = new ArrayList<>();
        result.add(allGroup);
        groupList.forEach(group->{
            List<UserInfo> infoList = new ArrayList<>();
            for (UserFollowing userFollowing : userFollowingList) {
                if(group.getId().equals(userFollowing.getGroupId())){
                    infoList.add(userFollowing.getUserInfo());
                }
            }
            group.setFollowingUserInfoLists(infoList);
            result.add(group);
        });
        return result;
    }

    @Override
    public List<UserFollowing> getUserFans(Long userId) {
        //1、获取用户粉丝列表
        List<UserFollowing> userFanList = userFollowingDao.getUserFans(userId);
        Set<Long> fanIds = userFanList.stream().map(UserFollowing::getUserId).collect(Collectors.toSet());
        List<UserInfo> userInfoList = new ArrayList<>();
        //2、根据粉丝的id查询所有粉丝的基本信息
        if(!CollectionUtils.isEmpty(fanIds)){
            userInfoList = userService.getUserInfoByUserIds(fanIds);
        }
        //3、查询当前用户是否已经关注该粉丝
        //当前用户的关注列表
        List<UserFollowing> userFollowingList = userFollowingDao.getUserFollowings(userId);
        for (UserFollowing userFan : userFanList) {
            for (UserInfo userInfo : userInfoList) {
                if(userFan.getUserId().equals(userInfo.getUserId())){
                    //补充用户粉丝基本信息
                    userInfo.setFollowed(false);
                    userFan.setUserInfo(userInfo);
                }
            }
            for (UserFollowing userFollowing : userFollowingList) {
                if(userFollowing.getFollowingId().equals(userFan.getUserId())){
                    //判断当前用户是否已经关注过该粉丝
                    userFan.getUserInfo().setFollowed(true);
                }
            }
        }
        return userFanList;
    }

    @Override
    public Long addUserFollowingGroups(FollowingGroup followingGroup) {
        Date now = new Date();
        followingGroup.setCreateTime(now);
        followingGroup.setUpdateTime(now);
        followingGroup.setType(UserConstant.USER_FOLLOWING_GROUP_TYPE_CUSTOM);
        return followingGroupService.addUserFollowingGroups(followingGroup);
    }

    @Override
    public List<FollowingGroup> getUserFollowingGroups(Long userId) {
        return followingGroupService.getUserFollowingGroups(userId);
    }

    @Override
    public List<UserInfo> checkFollowingStatus(List<UserInfo> userInfoList, Long userId) {
        //1、获取当前用户已经关注的用户信息
        List<UserFollowing> userFollowingList = userFollowingDao.getUserFollowings(userId);
        for (UserInfo userInfo : userInfoList) {
            userInfo.setFollowed(false);
            //2、如果搜索得到的用户中有我们关注的用户，那么更新这些用户的关注状态为已关注
            for (UserFollowing userFollowing : userFollowingList) {
                if(userFollowing.getFollowingId().equals(userInfo.getUserId())){
                    userInfo.setFollowed(true);
                }
            }
        }
        return userInfoList;
    }
}
